package com.ruoyi.animalManagement.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.ArrayList;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.animalManagement.domain.LmisQuaRecord;
import com.ruoyi.animalManagement.service.ILmisQuaRecordService;
import com.ruoyi.animalManagement.service.ILmisAnimalService;
import com.ruoyi.animalManagement.domain.LmisAnimal;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.animalManagement.domain.LmisQuaRecordItem;
import com.ruoyi.animalManagement.service.ILmisQuaRecordItemService;
import com.ruoyi.animalManagement.domain.LmisQuaItem;
import com.ruoyi.animalManagement.service.ILmisQuaItemService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 检疫纪录Controller
 * 
 * @author wj
 * @date 2025-08-18
 */
@RestController
@RequestMapping("/animalManagement/quaRecord")
public class LmisQuaRecordController extends BaseController
{
    @Autowired
    private ILmisQuaRecordService lmisQuaRecordService;
    @Autowired
    private ILmisAnimalService lmisAnimalService;
    @Autowired
    private ILmisQuaRecordItemService lmisQuaRecordItemService;
    @Autowired
    private ILmisQuaItemService lmisQuaItemService;

    /**
     * 查询检疫纪录列表
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(LmisQuaRecord lmisQuaRecord)
    {
        startPage();
        List<LmisQuaRecord> list = lmisQuaRecordService.selectLmisQuaRecordList(lmisQuaRecord);
        return getDataTable(list);
    }

    /**
     * 导出检疫纪录列表
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:export')")
    @Log(title = "检疫纪录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LmisQuaRecord lmisQuaRecord)
    {
        List<LmisQuaRecord> list = lmisQuaRecordService.selectLmisQuaRecordList(lmisQuaRecord);
        ExcelUtil<LmisQuaRecord> util = new ExcelUtil<LmisQuaRecord>(LmisQuaRecord.class);
        util.exportExcel(response, list, "检疫纪录数据");
    }

    /**
     * 获取检疫纪录详细信息
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:query')")
    @GetMapping(value = "/{quaRecordId}")
    public AjaxResult getInfo(@PathVariable("quaRecordId") Long quaRecordId)
    {
        return success(lmisQuaRecordService.selectLmisQuaRecordByQuaRecordId(quaRecordId));
    }

    /**
     * 新增检疫纪录
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:add')")
    @Log(title = "检疫纪录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LmisQuaRecord lmisQuaRecord)
    {
        return toAjax(lmisQuaRecordService.insertLmisQuaRecord(lmisQuaRecord));
    }

    /**
     * 修改检疫纪录
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:edit')")
    @Log(title = "检疫纪录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LmisQuaRecord lmisQuaRecord)
    {
        return toAjax(lmisQuaRecordService.updateLmisQuaRecord(lmisQuaRecord));
    }

    /**
     * 删除检疫纪录
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:remove')")
    @Log(title = "检疫纪录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{quaRecordIds}")
    public AjaxResult remove(@PathVariable Long[] quaRecordIds)
    {
        return toAjax(lmisQuaRecordService.deleteLmisQuaRecordByQuaRecordIds(quaRecordIds));
    }

    /**
     * 查询检疫记录项目明细
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:query')")
    @GetMapping("/item/list")
    public AjaxResult listItems(LmisQuaRecordItem item)
    {
        List<LmisQuaRecordItem> list = lmisQuaRecordItemService.selectLmisQuaRecordItemList(item);
        return success(list);
    }

    /**
     * 发起检疫：根据选择的动物与检疫项目，批量生成检疫记录，流程状态以overallResult为空表示“已发起”
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:add')")
    @Log(title = "检疫纪录-发起", businessType = BusinessType.INSERT)
    @PostMapping("/initiate")
    @Transactional
    public AjaxResult initiate(@RequestBody Map<String, Object> payload)
    {
        try {
            String quaType = String.valueOf(payload.get("quaType"));
            String quaTimeStr = String.valueOf(payload.get("quaTime"));
            Object userNameObj = payload.get("userName");
            Long userName = userNameObj == null || "null".equals(String.valueOf(userNameObj)) ? null : Long.valueOf(String.valueOf(userNameObj));

            @SuppressWarnings("unchecked")
            ArrayList<Map<String, Object>> animals = (ArrayList<Map<String, Object>>) payload.get("animals");
            @SuppressWarnings("unchecked")
            ArrayList<Map<String, Object>> quaItems = (ArrayList<Map<String, Object>>) payload.get("quaItems");

            if (animals == null || animals.isEmpty() || quaItems == null || quaItems.isEmpty())
            {
                return AjaxResult.error("动物或检疫项目不能为空");
            }

            Date quaTime = null;
            if (quaTimeStr != null && quaTimeStr.length() > 0)
            {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    quaTime = sdf.parse(quaTimeStr);
                } catch (ParseException e) {
                    return AjaxResult.error("检疫时间格式不正确");
                }
            }

            int rows = 0;
            for (Map<String, Object> animal : animals)
            {
                Long animalId = animal.get("animalId") == null ? null : Long.valueOf(String.valueOf(animal.get("animalId")));
                if (animalId == null) {
                    continue;
                }
                // 先插入主记录（一个动物一条主记录）
                LmisQuaRecord record = new LmisQuaRecord();
                record.setAnimalId(animalId);
                record.setQuaType(quaType);
                record.setQuaTime(quaTime);
                record.setUserName(userName);
                record.setDelFlag("0");
                // 发起检疫时，流程状态置为已发起（1）
                record.setRecordStatus("1");
                rows += lmisQuaRecordService.insertLmisQuaRecord(record);

                // 插入明细
                for (Map<String, Object> item : quaItems)
                {
                    Long quaItemId = item.get("quaItemId") == null ? null : Long.valueOf(String.valueOf(item.get("quaItemId")));
                    LmisQuaRecordItem detail = new LmisQuaRecordItem();
                    detail.setQuaRecordId(record.getQuaRecordId());
                    detail.setQuaItemId(quaItemId);
                    detail.setDelFlag("0");
                    lmisQuaRecordItemService.insertLmisQuaRecordItem(detail);
                }
            }
            return toAjax(rows);
        } catch (Exception ex) {
            return AjaxResult.error("发起检疫失败：" + ex.getMessage());
        }
    }

    /**
     * 检疫录入：逐项写入检测结果，按项目更新overallResult，附件字段写入结果详情
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:edit')")
    @Log(title = "检疫纪录-录入", businessType = BusinessType.UPDATE)
    @PutMapping("/input")
    @Transactional
    public AjaxResult input(@RequestBody Map<String, Object> payload)
    {
        try {
            Long quaRecordId = payload.get("quaRecordId") == null ? null : Long.valueOf(String.valueOf(payload.get("quaRecordId")));
            @SuppressWarnings("unchecked")
            ArrayList<Map<String, Object>> quaItems = (ArrayList<Map<String, Object>>) payload.get("quaItems");
            if (quaRecordId == null || quaItems == null || quaItems.isEmpty())
            {
                return AjaxResult.error("检疫记录或检疫项目不能为空");
            }

            int rows = 0;
            for (Map<String, Object> item : quaItems)
            {
                Long quaItemId = item.get("quaItemId") == null ? null : Long.valueOf(String.valueOf(item.get("quaItemId")));
                String testResult = item.get("testResult") == null ? null : String.valueOf(item.get("testResult"));
                Boolean isQualified = item.get("isQualified") == null ? null : Boolean.valueOf(String.valueOf(item.get("isQualified")));

                // 更新或插入明细
                LmisQuaRecordItem query = new LmisQuaRecordItem();
                query.setQuaRecordId(quaRecordId);
                query.setQuaItemId(quaItemId);
                List<LmisQuaRecordItem> details = lmisQuaRecordItemService.selectLmisQuaRecordItemList(query);
                LmisQuaRecordItem toSave = details != null && !details.isEmpty() ? details.get(0) : new LmisQuaRecordItem();
                toSave.setQuaRecordId(quaRecordId);
                toSave.setQuaItemId(quaItemId);
                toSave.setTestResult(testResult);
                toSave.setIsQualified(isQualified != null && isQualified ? 1 : 0);
                toSave.setDelFlag("0");
                if (toSave.getQuaRecordItemId() == null) {
                    rows += lmisQuaRecordItemService.insertLmisQuaRecordItem(toSave);
                } else {
                    rows += lmisQuaRecordItemService.updateLmisQuaRecordItem(toSave);
                }
            }

            // 计算整体结果并更新主记录（关键项目优先，如果存在关键项目，则全部关键项目需合格）
            LmisQuaRecordItem sumQuery = new LmisQuaRecordItem();
            sumQuery.setQuaRecordId(quaRecordId);
            List<LmisQuaRecordItem> allItems = lmisQuaRecordItemService.selectLmisQuaRecordItemList(sumQuery);
            // 构造 quaItemId -> isQualified 映射
            java.util.Map<Long, Integer> itemQualifiedMap = new java.util.HashMap<>();
            for (LmisQuaRecordItem it : allItems) {
                itemQualifiedMap.put(it.getQuaItemId(), it.getIsQualified());
            }
            // 查询该检疫类型的全部项目，以确定关键项目
            LmisQuaItem itemQuery = new LmisQuaItem();
            LmisQuaRecord main = lmisQuaRecordService.selectLmisQuaRecordByQuaRecordId(quaRecordId);
            if (main != null) {
                itemQuery.setQuaType(main.getQuaType());
            }
            java.util.List<LmisQuaItem> typeItems = lmisQuaItemService.selectLmisQuaItemList(itemQuery);

            boolean hasKey = false;
            boolean keyAllQualified = true;
            for (LmisQuaItem qi : typeItems) {
                if (qi.getIsKeyItem() != null && qi.getIsKeyItem() == 1) {
                    hasKey = true;
                    Integer q = itemQualifiedMap.get(qi.getQuaItemId());
                    if (q == null || q != 1) {
                        keyAllQualified = false;
                        break;
                    }
                }
            }
            boolean overall = false;
            if (hasKey) {
                overall = keyAllQualified;
            } else {
                boolean allQualified = allItems.stream().allMatch(d -> d.getIsQualified() != null && d.getIsQualified() == 1);
                overall = allQualified;
            }
            if (main != null) {
                main.setOverallResult(overall ? 1L : 0L);
                // 检疫录入完成，流程状态置为已检疫（2）
                main.setRecordStatus("2");
                lmisQuaRecordService.updateLmisQuaRecord(main);
            }

            return toAjax(rows);
        } catch (Exception ex) {
            return AjaxResult.error("检疫录入失败：" + ex.getMessage());
        }
    }

    /**
     * 分配笼位：更新动物cageId，并将位置写入检疫记录position
     */
    @PreAuthorize("@ss.hasPermi('animalManagement:quaRecord:edit')")
    @Log(title = "检疫纪录-分配笼位", businessType = BusinessType.UPDATE)
    @PutMapping("/assignCage")
    @Transactional
    public AjaxResult assignCage(@RequestBody Map<String, Object> payload)
    {
        try {
            Long animalId = payload.get("animalId") == null ? null : Long.valueOf(String.valueOf(payload.get("animalId")));
            Long cageId = payload.get("cageId") == null ? null : Long.valueOf(String.valueOf(payload.get("cageId")));
            String position = payload.get("position") == null ? null : String.valueOf(payload.get("position"));

            if (animalId == null || cageId == null)
            {
                return AjaxResult.error("参数不完整");
            }

            // 更新动物的笼位
            LmisAnimal animal = lmisAnimalService.selectLmisAnimalByAnimalId(animalId);
            if (animal == null)
            {
                return AjaxResult.error("动物不存在");
            }
            animal.setCageId(cageId);
            int rows = lmisAnimalService.updateLmisAnimal(animal);

            // 为该动物的所有未写位置的检疫记录写入位置（简化处理）
            LmisQuaRecord condition = new LmisQuaRecord();
            condition.setAnimalId(animalId);
            List<LmisQuaRecord> records = lmisQuaRecordService.selectLmisQuaRecordList(condition);
            if (records != null)
            {
                for (LmisQuaRecord r : records)
                {
                    if (r.getPosition() == null || r.getPosition().length() == 0)
                    {
                        r.setPosition(position);
                        lmisQuaRecordService.updateLmisQuaRecord(r);
                    }
                }
            }

            return toAjax(rows);
        } catch (Exception ex) {
            return AjaxResult.error("分配笼位失败：" + ex.getMessage());
        }
    }
}
